package com.software.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.druid.util.StringUtils;
import com.software.dao.impl.MessageDetailDaoImpl;
import com.software.domain.MessageDetailBean;
import com.software.model.DrmAgentAmountLog;
import com.software.model.DrmAgentIntroduce;
import com.software.model.DrmArticles;
import com.software.model.DrmUser;
import com.software.model.PageListModel;
import com.software.model.PageModel;
import com.software.service.AgentService;
import com.software.service.ImgMngService;
import com.software.service.IntroduceService;
import com.software.service.StuMngService;
import com.software.utils.Constants;
import com.software.utils.DateUtils;
import com.software.utils.IdCreater;

@Controller("agentController")
@RequestMapping(value = "/agent/*")
public class AgentController extends BaseController {

    @Autowired
    private AgentService agentService;
    
    @Autowired
    private IntroduceService introduceService;
    
    @Autowired
    private MessageDetailDaoImpl mongo;
    
    @Autowired
    private StuMngService stuMngService;

    @Autowired
    private ImgMngService imgMngService;
    
    /**
     * 代理商管理 主页面
     * @param model
     * @param res
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "agentMain", method = RequestMethod.GET)
    public ModelAndView mainPage(Model model, HttpServletResponse res, HttpServletRequest req) throws Exception {
        ModelAndView view = new ModelAndView();
        Long userId = super.getUserIdInSession(req);
        DrmUser amount = agentService.searchUserAmount(userId);
        if(null != amount) {
            amount.setUserHimg(StringUtils.isEmpty(amount.getUserHimg())? "": Constants.IMG_URL + amount.getUserHimg()+ "?w=48&h=48");
        }
        view.addObject("userAmount", amount);
        view.setViewName("agent/drm_main");
        return view;
        
    }
    
    /**
     * 
     * 根据t 类型返回不同的 html页面
     * @param t
     * @param res
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "htmlcontent")
    public ModelAndView changeHtmlContent(@RequestBody PageModel vo, HttpServletResponse res, HttpServletRequest req) throws Exception {
        ModelAndView map = new ModelAndView();
        // 默认页面翻页数据加载
        if(0 == vo.getPageNo() || 0 == vo.getPageSize()) {
            viewPageSet(vo);
        }
        
        pushModelAndView(map,vo,    req);
        

        
        return map;
    }
    
    /**
     * 通过页面ID   返回对应的 数据及JSP页面
     * @param view
     * @param tp
     */
    private void pushModelAndView(ModelAndView view, PageModel vo,HttpServletRequest req) {

        if (Constants.AGNAV_00.equals(vo.getType())) {
            // 首页
            banner(view, vo);
        } else if (Constants.AGNAV_01.equals(vo.getType())) {
            // 资讯
            info(view, vo, req);
        } else if (Constants.AGNAV_02.equals(vo.getType())) {
            // 活动
            act(view, vo, req);
        } else if (Constants.AGNAV_03.equals(vo.getType())) {
            // 中心介绍
            cent(view, vo, req);
        } else if (Constants.AGNAV_04.equals(vo.getType())) {
            // 相册管理
            pic(view, vo, req);
        } else if (Constants.AGNAV_05.equals(vo.getType())) {
            // 学员管理
            stu(view, vo, req);
        } else if (Constants.AGNAV_06.equals(vo.getType())) {
            // 我的账户
            acc(view, vo, req);
        }

    };
    
    /**
     * 
     * 删除资讯
     * @param t
     * @param res
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "delInfo")
    public ModelAndView delInfo(@RequestBody PageModel webParam, HttpServletResponse res, HttpServletRequest req) throws Exception {
        Long userId = super.getUserIdInSession(req);
        if (!StringUtils.isEmpty(webParam.getIds())) {
            String arrayid[] = webParam.getIds().split("\\|");
            List<DrmArticles> list = new ArrayList<DrmArticles>();
            for (String id : arrayid) {
                if (StringUtils.isEmpty(id)) {
                    continue;
                }
                DrmArticles art = new DrmArticles();
                art.setId(Long.valueOf(id));
                art.setArticleTpDel(webParam.getArticleTp());
                art.setArticleUid(userId);
                list.add(art);
            }
            agentService.updateInfoDel(list);
        }
        
        ModelAndView map = new ModelAndView();
        PageModel vo = new PageModel();
        // 默认页面翻页数据加载
        viewPageSet(vo);
        vo.setType(webParam.getType());
        vo.setArticleTp(webParam.getArticleTp());
        pushModelAndView(map,vo,    req);
        return map;
        
    }
    
    
    /**
     * 
     * 置顶操作
     * @param t
     * @param res
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "setTop")
    public ModelAndView setTopUpdata(@RequestBody PageModel webParam, HttpServletResponse res, HttpServletRequest req) throws Exception {
        if (!StringUtils.isEmpty(webParam.getIds())) {
            String arrayid[] = webParam.getIds().split("\\|");
            List<DrmArticles> list = new ArrayList<DrmArticles>();
            for (String id : arrayid) {
                if (StringUtils.isEmpty(id)) {
                    continue;
                }
                DrmArticles art = new DrmArticles();
                art.setId(Long.valueOf(id));
                art.setArticleTp(webParam.getArticleTp());
                art.setArticleHeadyn(Constants.YES);
                art.setArticleUid( super.getUserIdInSession(req));
                list.add(art);
            }
            agentService.updateArtHeader(list);
        }
        
        ModelAndView map = new ModelAndView();
        PageModel vo = new PageModel();
        // 默认页面翻页数据加载
        viewPageSet(vo);
        vo.setType(webParam.getType());
        vo.setArticleTp(webParam.getArticleTp());
        pushModelAndView(map,vo,    req);
        return map;
        
    }
    
    /**
     * 
     * 取消置顶操作
     * @param t
     * @param res
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "cancelTop")
    public ModelAndView cancelTopUpdata(@RequestBody PageModel webParam, HttpServletResponse res, HttpServletRequest req) throws Exception {
        if (!StringUtils.isEmpty(webParam.getIds())) {
            String arrayid[] = webParam.getIds().split("\\|");
            List<DrmArticles> list = new ArrayList<DrmArticles>();
            for (String id : arrayid) {
                if (StringUtils.isEmpty(id)) {
                    continue;
                }
                DrmArticles art = new DrmArticles();
                art.setId(Long.valueOf(id));
                art.setArticleTp(webParam.getArticleTp());
                art.setArticleHeadyn(Constants.NO);
                art.setArticleDelyn(Constants.DEL_NO);
                art.setArticleUid( super.getUserIdInSession(req));
                list.add(art);
            }
            agentService.updateArtHeader(list);
        }
        
        ModelAndView map = new ModelAndView();
        PageModel vo = new PageModel();
        // 默认页面翻页数据加载
        viewPageSet(vo);
        vo.setType(webParam.getType());
        vo.setArticleTp(webParam.getArticleTp());
        pushModelAndView(map,vo,    req);
        return map;
        
    }
    
    

    
    /**
     * 跳转页面， 查询数据库，返回数据
     * @param view
     */
    private void banner(ModelAndView view , PageModel vo){

        
        view.setViewName("agent/banner");
    }
    
    /**
     * 我的账户 Init
     * @param view
     */
    private void acc(ModelAndView view , PageModel vo , HttpServletRequest req){
        
        DrmUser amount = agentService.searchUserAmount( super.getUserIdInSession(req));
        if(null != amount) {
            amount.setUserHimg(StringUtils.isEmpty(amount.getUserHimg())? "": Constants.IMG_URL + amount.getUserHimg()+ "?w=48&h=48");
        }
        view.addObject("userAmount", amount);
        
        List<DrmAgentAmountLog> logList = agentService.searchUserAmountLog( super.getUserIdInSession(req));
        
        view.addObject("logList", logList);
        
        view.addObject("logsize", logList.size());
        
        view.setViewName("agent/acc");
    }
    
    /**
     * 资讯 init
     * @param view
     */
    private void info(ModelAndView view ,PageModel vo , HttpServletRequest req){
        // 查询数据库  返回数据 
        vo.setArticleTp(vo.getArticleTp());
        vo.setIds(super.getUserIdInSession(req).toString());
        PageListModel val = agentService.queryInfo(vo);
        
        view.addObject("infoList", val.getShowData());
        
        super.setPageData(view, val);

        view.setViewName("agent/info");
    }
    
    /**
     * 中心介绍
     * @param view
     */
    private void cent(ModelAndView view , PageModel vo, HttpServletRequest req){
        
        DrmAgentIntroduce data = new DrmAgentIntroduce();
        // TODO 
        data.setAgentId( super.getUserIdInSession(req));
        DrmAgentIntroduce webData = introduceService.queryIntroduce(data);
        if(null != webData) {
            webData.setIntroduceTxt(Constants.TXT_URL + webData.getIntroduceTxt());
        }
        
        view.addObject("data",  webData);
        view.setViewName("agent/cent");
    }
    
    /**
     * 相册管理 init
     * @param view
     */
    private void pic(ModelAndView view, PageModel vo, HttpServletRequest req){
    	
    	vo.setIds(super.getUserIdInSession(req).toString());
        PageListModel val = imgMngService.searchAgentImgList(vo);
        view.addObject("imgList",  val);
        view.setViewName("agent/pic");
    }

    /**
     * 学员管理 init
     * @param view
     */
    private void stu(ModelAndView view, PageModel vo, HttpServletRequest req){
        
//        setPageData(  view,224,22,vo.getPageNo(),vo.getType());
        
        view.setViewName("agent/stu");
    }
    
    /**
     * 活动 init
     * @param view
     */
    private void act(ModelAndView view,PageModel vo, HttpServletRequest req){
        
        vo.setArticleTp(Constants.ARTICLE_TP_10);
        vo.setIds( super.getUserIdInSession(req).toString());
        PageListModel val = agentService.queryInfo(vo);
        
        view.addObject("actList", val.getShowData());
        
        super.setPageData(view, val);
        
        view.setViewName("agent/act");
    }
    

    /**
     * 添加资讯 init
     * @param view
     */
    @RequestMapping(value = "addInfoInit")
    public String addInfoInit(HttpServletResponse res, HttpServletRequest req){
        
        return    "agent/addinfo";
    }
    
    /**
     * 编辑咨询 获取数据 init
     * @param view
     */
    @RequestMapping(value = "editInfoInit")
	@ResponseBody
    public DrmArticles editInfoInit(@RequestBody PageModel webParam ,HttpServletResponse res, HttpServletRequest req){
    	 DrmArticles date = new  DrmArticles();
    	 if (!StringUtils.isEmpty(webParam.getIds())) {
    		 date = agentService.searchInfoDetails(webParam.getIds());
    		 date.setArticleContent(Constants.TXT_URL + date.getArticleContent());
         }
        
         return  date;
    }
    
    /**
     * 添加资讯 保存
     * @param view
     */
    @RequestMapping(value = "addInfo" ,produces = "text/html;charset=UTF-8")
    public ModelAndView addInfo(@RequestBody DrmArticles atr,HttpServletResponse res, HttpServletRequest req){
    	MessageDetailBean bean = new MessageDetailBean();
        if(0 == atr.getFlag()) {
        	atr.setBrowerCnt(0);
        	atr.setId(IdCreater.getId());
        	bean.setCreateTime(DateUtils.getCurrentDateTime());
        }
        
        bean.setProductId((atr.getId().toString()));
        bean.setDetailContent(atr.getArticleContent());
        bean.setSellerId(001);
        
        
        MessageDetailBean newMongo = mongo.save(bean);
        System.out.println("id = " + newMongo.getId());
        atr.setArticleDesc(atr.getArticleContent().length() > 20 ? atr.getArticleContent().substring(0,20):atr.getArticleContent());
        atr.setArticleContent(newMongo.getId());
        atr.setArticleCid(super.getUserIdInSession(req));
        if(0 == atr.getFlag()) {
        	agentService.saveDrmArticles(atr);
        } else {
        	agentService.updateDrmArticles(atr);
        }
       
        ModelAndView map = new ModelAndView();
        PageModel vo = new PageModel();
        // 默认页面翻页数据加载
        viewPageSet(vo);
        vo.setType(atr.getType());
        vo.setArticleTp(atr.getArticleTp());
        pushModelAndView(map,vo,req);
        return map;
    }
    
    /**
     * 点击title
     * @param view
     */
    @RequestMapping(value = "clickTitle")
    public void clickTitle(@RequestBody PageModel vo, HttpServletResponse res, HttpServletRequest req){
        DrmArticles atr = new DrmArticles();
        atr.setId(Long.valueOf(vo.getIds()));
        atr.setArticleTp(vo.getArticleTp());
        atr.setArticleUid( super.getUserIdInSession(req));
        agentService.updateArtCnt(atr);
        
    }
    
    /**
     * 
     * 点击排序操作
     * @param t
     * @param res
     * @param req
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "sortEvent")
    public ModelAndView sortClickEvent(@RequestBody PageModel vo,
            HttpServletResponse res, HttpServletRequest req) throws Exception {
        ModelAndView map = new ModelAndView();
        // 默认页面翻页数据加载
        vo.setPageNow(1);
        vo.setPageNo(1);
        vo.setPageSize(8);
        pushModelAndView(map, vo,req);
        return map;
    }
    
}
